//
//  AccountBindViewController.m
//  MingShi
//
//  Created by MJiao on 15/7/12.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "AccountBindViewController.h"
#import "KVNProgress.h"
#import "AFHTTPRequestOperationManager.h"
#import "MingShiTencentSessionDelegate.h"
#import "User.h"
#import "UserManager.h"
#import  "CommonUtils.h"
#import "NSString+Emoji.h"

@interface AccountBindViewController ()

@end

@implementation AccountBindViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    NSLog(self.QQAvatar);
//    NSLog(self.QQGender);
//    NSLog(self.QQNickname);

}
- (IBAction)btnSubmitBindAction:(id)sender {
    NSString *account = [self.tfAccount text];
    NSString *pwd = [self.tfPwd text];
    NSString *confirmPwd = [self.tfPwdConfirm text];

    if (account == nil || account.length == 0) {
        [KVNProgress showErrorWithStatus:@"请输入用户名"];
        [self.tfAccount becomeFirstResponder];
        return;
    }
    if (pwd == nil || pwd.length == 0) {
        [KVNProgress showErrorWithStatus:@"请输入密码"];
        [self.tfPwd becomeFirstResponder];
        return;
    }
    if (confirmPwd == nil || confirmPwd.length == 0) {
        [KVNProgress showErrorWithStatus:@"请再次输入密码"];
        [self.tfPwdConfirm becomeFirstResponder];
        return;
    }
    if(![pwd isEqualToString: confirmPwd]){
        [KVNProgress showErrorWithStatus:@"密码不匹配"];
        [self.tfPwdConfirm becomeFirstResponder];
        return;
    }


    // Adds a status below the circle
    [KVNProgress showWithStatus:@"账号绑定中..."];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    
    NSString *userName =   [self.QQNickname stringByReplacingEmojiUnicodeWith:@""];
    
//            [self.QQNickname stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *imageUrl = self.QQAvatar;
    NSString *loingName = account;
//            [account stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *openId = [MingShiTencentSessionDelegate getinstance].oauth.openId;
    NSString *pssword = [pwd stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *sex = self.QQGender;
            //[self.QQGender stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *accessToken = [MingShiTencentSessionDelegate getinstance].oauth.accessToken;

    NSString *urlString = @"http://121.41.91.36:8888/api/users/registerByQQ";

    NSDictionary *parameters = @{
            @"userName": userName,
            @"imageUrl": imageUrl,
            @"loingName": loingName,
            @"address" : self.QQCity,
            @"channelId" : [[UserManager shareUserManager] bdPushChannelId],
            @"deviceType" : @"4",
            @"openId": openId,
            @"pssword": pssword,
            @"sex": sex,
            @"accessToken": accessToken
    };

    [manager GET:urlString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束登陆提示
        [KVNProgress dismiss];

        NSString *code = [responseObject objectForKey:@"code"];
        NSString *msg = [responseObject objectForKey:@"msg"];

        //登录失败
        if (code == nil || ![code isEqualToString:@"00"]) {
            [KVNProgress showErrorWithStatus:msg];
            return;
        }

        //发送重新登陆通知
        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
        [notificationCenter postNotificationName:@"reLoin" object:self userInfo:userInfo];


        
        [KVNProgress showSuccessWithStatus:msg completion:^{
            id obj = [responseObject objectForKey:@"result"];
            NSString *loingName = [obj objectForKey:@"loingName"];
            NSString *sex = [obj objectForKey:@"sex"];
            NSString *address = [obj objectForKey:@"address"];
            NSString *creatTime = [obj objectForKey:@"creatTime"];
            NSString *wenwen = [obj objectForKey:@"wenwen"];
            NSString *moneys = [obj objectForKey:@"moneys"];
            NSString *imageUrl = [obj objectForKey:@"imageUrl"];
            NSString *gradeName = [obj objectForKey:@"gradeName"];
            NSString *schoolName = [obj objectForKey:@"schoolName"];
            NSString *email = [obj objectForKey:@"email"];
            NSString *slogins = [obj objectForKey:@"slogins"];
            NSInteger userId = [[obj objectForKey:@"id"] integerValue];
            NSInteger twnum = [[obj objectForKey:@"twnum"] integerValue];
            NSString *openId = [obj objectForKey:@"openId"];
            NSString *accessToken = [obj objectForKey:@"accessToken"];
            NSString *themeImage = [obj objectForKey:@"themeImage"];
            NSInteger age = 0;

            @try {
                age = [[obj objectForKey:@"brith"] integerValue];
            }
            @catch (NSException *exception) {
                NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
            }

            User *user = [[User alloc] init];
            user.account = loingName;
            user.pwd = pwd;
            user.sex = sex;
            user.address = address;
            user.creatTime = creatTime;
            user.wenwen = wenwen;
            user.moneys = moneys;
            user.imageUrl = imageUrl;
            user.gradeName = gradeName;
            user.schoolName = schoolName;
            user.email = email;
            user.slogins = slogins;
            user.userId = userId;
            user.twnum = twnum;
            user.openId = openId;
            user.accessToken = accessToken;
            user.userName = userName;
            user.age = age;
            user.themeImage = themeImage;


            [[UserManager shareUserManager] setCurUser:user];
            //保存登录信息
            [[UserManager shareUserManager] saveUserToDisk:user];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        // 结束登陆提示
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络错误"];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
